import { getStream } from '../Core/connect'
import * as MathUtils from '../Math/MathUtils'

export class WFSServer {
    readonly type: string
    url: string
    uuid: string
    baseUrl: string
    constructor(url: string, layerName: string) {
        this.type = 'WFSServer'
        this.url = url
        this.uuid = MathUtils.generateUUID()
        this.baseUrl = this.getUrl(url, layerName)
    }

    private getUrl(url: string, layerName: string) {
        const baseUrl = url + '/ows?service=WFS&version=1.0.0&request=GetFeature&outputFormat=application%2Fjson&srsname=EPSG%3A4326&maxFeatures=1&typeName=' + layerName + '&bbox='
        return baseUrl
    }

    addWFSQuery(fun: Function) {
        const sessionId = MathUtils.generateUUID()
        const baseUrl = this.baseUrl
        const stream = getStream()
        const str = {gisFunction: 'addWFSQuery', url: `${baseUrl}`, sessionId: sessionId}
        stream.emitUIInteraction(str)
        const getWFSReady = (data: string) => {
            const returnData = JSON.parse(data)
            if (returnData.sessionId === sessionId) {
                fun(returnData)
            }
        }
        stream.addResponseEventListener(`getWFS${sessionId}`, getWFSReady)
    }

    // 删除本条WFS查询
    deleteWFSQuery() {
        const stream = getStream()
        const str = {gisFunction: 'deleteWFSQuery', url: `${this.baseUrl}`}
        stream.emitUIInteraction(str)
    }

    // 删除所有WFS查询
    clearWFS() {
        const stream = getStream()
        const str = {gisFunction: 'clearWFS'}
        stream.emitUIInteraction(str)
    }
}